package org.vision.contactsmanager.dao;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.vision.contactsmanager.bean.MyContacts;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.graphics.Bitmap;
import android.util.Log;

public class ContactsManagerDbAdater {
    public static final String TAG = "ContactsManagerDbAdater";
    public static final String DATABASE_NAME = "contactsmanager.db";
    public static final int DATABASE_VERSON = 3;
    public static final String TABLE_CONTACTS = "contacts";
    public static final String TABLE_GROUPS = "groups";
    public static final String TABLECONTACTS = "create table contacts(" + "_id INTEGER PRIMARY KEY AUTOINCREMENT," + //rowID
            "contactsContractId TEXT," + //ContactsContract本地联系ID
            "name TEXT  NOT NULL," + //姓名
            "contactIcon BLOB," + //联系人图标
            "telPhone TEXT NOT NULL," + //电话号码
            "groupName TEXT," + //所属组名
            "birthday TEXT," + //生日
            "address TEXT," + //地址
            "email TEXT NOT NULL," + //邮箱
            "description TEXT NOT NULL," + //好友描述
            "createTime TEXT," + //创建时间
            "modifyTime TEXT" + //修改时间
            ");";
    public static final String TABLEGROUPS = "create table groups(" + "_id INTEGER PRIMARY KEY," + //rowId
            "groupName TEXT UNIQUE NOT NULL," + //组名
            "createTime TEXT," + //创建时间
            "modifyTime TEXT" + //修改时间
            ");";

    private Context context;
    private DatabaseHelper dbHelper;
    private SQLiteDatabase mSQLiteDatabase = null;
    public List<MyContacts> contactList = new ArrayList<MyContacts>();
    //用来操作本地通讯录的工具类
    public LocalContactsUtils lcu;

    public ContactsManagerDbAdater(Context context) {
        this.context = context;
        lcu = new LocalContactsUtils(context);
    }

    public void open() {
        dbHelper = new DatabaseHelper(context);
        mSQLiteDatabase = dbHelper.getWritableDatabase();
    }

    /**
     * 获取本地的手机已经存在的通讯录
     */
    public void getContactsContract() {
        //从本地手机中获取
        lcu.getLocalContact();
        //从SIM卡中获取
        lcu.getSimContact("content://icc/adn");
        //发现有得手机的SIM卡联系人在这个路径...所以都取了(每次验证是否已存在)
        lcu.getSimContact("content://sim/adn");
        contactList = lcu.getContactList();
    }

    public void close() {
        dbHelper.close();
    }

    private class DatabaseHelper extends SQLiteOpenHelper {

        public DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSON);
        }

        @Override
        public void onOpen(SQLiteDatabase db) {
            super.onOpen(db);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            Log.i("TAG", "create table start...");

            db.execSQL(TABLECONTACTS);
            db.execSQL(TABLEGROUPS);
            //创建默认的组,跟QQ类似
            String defaultGroups[] = {"我的好友", "朋友", "同学", "企业好友", "家人"};
            String intGroupSql = "insert into groups values(?,?,null,null)";
            for (int i = 0; i < defaultGroups.length; i++) {
                Object[] bindArgs = {i + 1, defaultGroups[i]};
                db.execSQL(intGroupSql, bindArgs);
            }

            //创建临时的联系人,默认都分组到我的好友中，跟QQ一样
            String intContactSql = "insert into contacts values(null,?,?,null,?,?,?,?,?,?,null,null)";
            for (int i = 0; i < contactList.size(); i++) {
                MyContacts mc = contactList.get(i);
                Object[] bindArgs = {mc.getContactsContractId(), mc.getName(), mc.getTelPhone(), defaultGroups[0],
                        "1987-2-2", "", "", ""};
                db.execSQL(intContactSql, bindArgs);
            }

            Log.i("TAG", "create table over...");
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            Log.i("TAG", "contactsmanager.db Upgrade...");
            db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);
            db.execSQL("DROP TABLE IF EXISTS " + TABLE_GROUPS);
            onCreate(db);

        }

    }

    //将头像转换成byte[]以便能将图片存到数据库
    public byte[] getBitmapByte(Bitmap bitmap) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
        try {
            out.flush();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
            Log.e(TAG, "transform byte exception");
        }
        return out.toByteArray();
    }

    //table contacts
    public static final String contacts_id = "_id";
    public static final String contacts_contactsContractId = "contactsContractId";
    public static final String contacts_icon = "contactIcon";
    public static final String contacts_name = "name";
    public static final String contacts_description = "description";
    public static final String contacts_telPhone = "telPhone";
    public static final String contacts_email = "email";
    String contactProjection[] = {contacts_id, contacts_contactsContractId, contacts_icon, contacts_name,
            contacts_description, contacts_telPhone, contacts_email};

    //table groups
    public static final String groups_id = "_id";
    public static final String groups_groupName = "groupName";
    String groupsProjection[] = {groups_id, groups_groupName};

    /**
     * 查找所有的联系人
     * @return 所有的联系人
     */
    public List<MyContacts> getAllContacts() {
        List<MyContacts> mcs = new ArrayList<MyContacts>();
        Cursor allContactsCursor = mSQLiteDatabase.query(TABLE_CONTACTS, contactProjection, null, null, null, null,
                null);

        int contactsContractIdColumn = allContactsCursor.getColumnIndex(contacts_contactsContractId);
        int contactsIconColumn = allContactsCursor.getColumnIndex(contacts_icon);
        int contactsNameColumn = allContactsCursor.getColumnIndex(contacts_name);
        int contactsDescriptionColumn = allContactsCursor.getColumnIndex(contacts_description);
        int contactsTelPhoneColumn = allContactsCursor.getColumnIndex(contacts_telPhone);
        int contactsEmailColumn = allContactsCursor.getColumnIndex(contacts_email);

        for (allContactsCursor.moveToFirst(); !allContactsCursor.isAfterLast(); allContactsCursor.moveToNext()) {
            MyContacts mc = new MyContacts();
            mc.setContactsContractId(allContactsCursor.getString(contactsContractIdColumn));
            mc.setContactIcon(allContactsCursor.getBlob(contactsIconColumn));
            mc.setName(allContactsCursor.getString(contactsNameColumn));
            mc.setDescription(allContactsCursor.getString(contactsDescriptionColumn));
            mc.setTelPhone(allContactsCursor.getString(contactsTelPhoneColumn));
            mc.setEmail(allContactsCursor.getString(contactsEmailColumn));

            mcs.add(mc);
        }
        return mcs;
    }

    //查找所有组
    public Cursor getAllGroups() {
        return mSQLiteDatabase.query(TABLE_GROUPS, groupsProjection, null, null, null, null, null);

    }

    //得到给定组的所有成员
    public Cursor getContactsByGroupName(String groupName) {
        return mSQLiteDatabase.query(TABLE_CONTACTS, contactProjection, "groupName='" + groupName + "'", null, null,
                null, null);
    }

    //统计给定组的人数
    public int getCountContactByGroupName(String groupName) {
        int count = 0;
        String sql = "select count(*) from contacts where groupName='" + groupName + "'";
        Cursor cursor = mSQLiteDatabase.rawQuery(sql, null);
        if (cursor.moveToFirst()) {
            count = cursor.getInt(0);
        }
        cursor.close();
        return count;
    }

    //同步更新contacts里groupName字段信息
    public void updateSyncData(String sql, Object[] Args) {
        mSQLiteDatabase.execSQL(sql, Args);
    }

    //查询联系人在哪个组
    public String checkContactGroup(String sql, String selectionArgs[]) {
        String groupName = "";
        Cursor cursor = mSQLiteDatabase.rawQuery(sql, selectionArgs);
        if (cursor.moveToFirst()) {
            groupName = cursor.getString(0);
        }
        cursor.close();
        return groupName;
    }

    //查询
    public Cursor getCursorBySql(String sql, String selectionArgs[]) {
        return mSQLiteDatabase.rawQuery(sql, selectionArgs);
    }

    //添加一个组
    public long inserDataToGroups(String groupName) {

        String formatTime = getSysNowTime();
        ContentValues content = new ContentValues();
        content.put(groups_groupName, groupName);
        content.put("createTime", formatTime);
        content.put("modifyTime", formatTime);
        return mSQLiteDatabase.insert(TABLE_GROUPS, null, content);

    }

    //删除一个组
    public int deleteDataFromGroups(String groupName) {
        return mSQLiteDatabase.delete(TABLE_GROUPS, "groupName='" + groupName + "'", null);
    }

    //更新一个组
    public int updateDataToGroups(String newgroupName, String oldgroupName) {
        String formatTime = getSysNowTime();
        ContentValues content = new ContentValues();
        content.put(groups_groupName, newgroupName);
        content.put("modifyTime", formatTime);
        return mSQLiteDatabase.update(TABLE_GROUPS, content, "groupName='" + oldgroupName + "'", null);
    }

    //添加一个联系人
    public long inserDataToContacts(MyContacts contactInfo) {
        //往本机联系人中插入联系人
        String contactsContractId = lcu.insertToLContact(contactInfo);
        //往该应用数据库中插入联系人
        String formatTime = getSysNowTime();
        ContentValues content = new ContentValues();
        content.put("contactsContractId", contactsContractId);
        content.put("name", contactInfo.getName());
        content.put("birthday", contactInfo.getBirthday());
        content.put("address", contactInfo.getAddress());
        content.put("telPhone", contactInfo.getTelPhone());
        content.put("email", contactInfo.getEmail());
        content.put("contactIcon", contactInfo.getContactIcon());
        content.put("description", contactInfo.getDescription());
        content.put("groupName", contactInfo.getGroupName());
        content.put("createTime", formatTime);
        content.put("modifyTime", formatTime);
        return mSQLiteDatabase.insert(TABLE_CONTACTS, null, content);

    }

    //删除一个联系人
    public int deleteDataFromContacts(MyContacts mc) {
        lcu.deleteFromLContact(mc);
        return mSQLiteDatabase.delete(TABLE_CONTACTS, "name='" + mc.getName() + "'", null);
    }

    /**
     * 更新联系人
     * contactInfo:用户重新编辑的联系人信息
     * name:编辑的是哪个联系人
     */
    public int updateDataToContacts(MyContacts contactInfo, String name) {
        String formatTime = getSysNowTime();
        ContentValues content = new ContentValues();
        content.put("name", contactInfo.getName());
        content.put("birthday", contactInfo.getBirthday());
        content.put("address", contactInfo.getAddress());
        content.put("telPhone", contactInfo.getTelPhone());
        content.put("email", contactInfo.getEmail());
        content.put("contactIcon", contactInfo.getContactIcon());
        content.put("description", contactInfo.getDescription());
        content.put("groupName", contactInfo.getGroupName());
        content.put("modifyTime", formatTime);
        //更新本地通讯录信息
        lcu.updateToLContact(contactInfo);
        return mSQLiteDatabase.update(TABLE_CONTACTS, content, "name=?", new String[] {name});
    }

    //get sysTime
    public String getSysNowTime() {
        Date now = new Date();
        java.text.DateFormat format = new java.text.SimpleDateFormat("yyyy-MM-dd HH:MM:ss");
        String formatTime = format.format(now);
        return formatTime;
    }

}
